package com.example;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyTwitter extends Activity implements OnClickListener {
  static final String TAG = "MyTwitter";
  private Twitter twitter;
  private SharedPreferences prefs;
  private Button buttonUpdate;
  private EditText textStatus;
  private LocationHelper locationHelper;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Find views by id
    buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
    textStatus = (EditText) findViewById(R.id.textStatus);
    twitter = new TwitterClient(getApplicationContext()).getTwitter();
    // Add listener
    buttonUpdate.setOnClickListener(this);

    // Initialize preferences
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs
        .registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
          public void onSharedPreferenceChanged(SharedPreferences arg0,
              String arg1) {
            twitter = null;
          }
        });

    // Screen orientation
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
      textStatus.setMinLines(3);
      buttonUpdate.setTextSize(22);
    }

    // Setup location helper
    locationHelper = new LocationHelper(this);
  }

  @Override
  public void onResume() {
    super.onResume();
    // Start the UpdaterService
    startService(new Intent(this, UpdaterService.class));
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    // Stop the UpdaterService
    stopService(new Intent(this, UpdaterService.class));
  }

  /** Called when Update button is clicked */
  public void onClick(View v) {
    String status = textStatus.getText().toString();
    String message = "Status set to: " + status;
    Log.d(TAG, message);

    // Ignore empty updates
    if (status.length() == 0)
      return;

    // Update status for location
    status = locationHelper.updateStatusForLocation(status);

    // Connect to twitter.com and update your status
    try {
      twitter.setStatus(status);
    } catch (TwitterException e) {
      Log.e(TAG, "Twitter exception: " + e);
    }
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
  }

 }